<template>
  <div class="compact-container">
    <!-- Compact search row -->
    <div class="search-row">
      <span class="search-label">入库仓库：</span>

      <el-select v-model="weahouseCode" placeholder="请选择入库仓库" class="search-select" size="small">
        <el-option v-for="item in Weahouse" :key="item.warehouse_code" :label="item.warehouse_name"
          :value="item.warehouse_code" />
      </el-select>
      <span class="search-label">入库订单编号：</span>
      <el-input v-model="code" size="small" class="search-input" />
      <span class="search-label">审核状态：</span>
      <el-select v-model="auditStatus1" size="small" class="search-input">
        <el-option label="待审核" value="0" />
        <el-option label="已审核" value="1" />
        <el-option label="已驳回" value="2" />
      </el-select>
      <el-button type="primary" size="small" @click="query">查询</el-button>
      <el-button size="small" @click="reset">重置</el-button>
      <div class="flex-grow"></div>
      <el-button type="primary" size="small" @click="exportToExcel">导出</el-button>
      <el-button type="primary" size="small" @click="addEdit">添加</el-button>
    </div>

    <el-divider style="margin: 6px 0" />

    <!-- Compact table area -->
    <div class="table-wrapper">
      <el-table :data="tableData" border style="width: 100%" :cell-style="{ textAlign: 'center', padding: '4px 0' }"
        :header-cell-style="{
          textAlign: 'center',
          background: '#f5f7fa',
          fontWeight: 'bold',
          position: 'sticky',
          top: 0,
          padding: '4px 0',
          height: '36px'
        }" :span-method="objectSpanMethod" ref="customerTable">
        <el-table-column fixed width="180px" prop="finished_goods_store_code" label="成品入库编号">
          <template #default="scope">
            <el-link type="primary" @click="infoPage(scope.row.finished_goods_store_code)">
              {{ scope.row.finished_goods_store_code }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column fixed width="180px" prop="warehouse_name" label="入库仓库" />
        <el-table-column fixed width="180px" prop="finished_goods_store_audit_status" label="审核状态">
          <template #default="scope">
            {{ scope.row.finished_goods_store_audit_status == '0' ? "待审核" :
              scope.row.finished_goods_store_audit_status == '1' ? "已审核" : "已驳回" }}
          </template>
        </el-table-column>
        <el-table-column prop="pro_name" label="产品名称" width="150px" />
        <el-table-column prop="pro_code" label="产品编号" width="180px" />
        <el-table-column prop="pro_brand" label="品牌" width="150px" />
        <el-table-column prop="pro_model" width="180px" label="规格型号" />
        <el-table-column prop="measure_id" label="单位" width="100px">
          <template #default="scope">
            {{ measureValue(scope.row.measure_id) }}
          </template>
        </el-table-column>
        <el-table-column prop="finished_goods_qty" width="100px" label="成品数量" />
        <el-table-column prop="unqualified_qty" width="100px" label="不合格数量" />
        <el-table-column prop="store_qty" label="入库数量" width="150px" />
        <el-table-column prop="store_total_qty" width="100px" label="入库总数" />
        <el-table-column prop="quality_testing_status" label="质检状态" width="200px">
          <template #default="scope">
            {{ scope.row.quality_testing_status == '0' ? "不合格" :
              scope.row.quality_testing_status == '1' ? "部分合格" : "全部合格" }}
          </template>
        </el-table-column>
        <el-table-column prop="quality_testing_by" label="质检员" width="200px" />
        <el-table-column prop="quality_testing_time" label="质检时间" width="200px">
          <template #default="scope">
            {{ scope.row.quality_testing_time.replace('T', ' ') }}
          </template>
        </el-table-column>
        <el-table-column prop="finished_goods_store_rep_id" label="入库员" width="200px">
          <template #default="scope">
            {{ userValue(scope.row.finished_goods_store_rep_id) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200px" prop="action">
          <template #default="scope">
            <div class="action-group">
              <el-button size="small" @click="handleEdit(scope.row)"
              :disabled="scope.row.finished_goods_store_audit_status === '1' || scope.row.finished_goods_store_audit_status === '2'">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)"
              :disabled="scope.row.finished_goods_store_audit_status === '1' || scope.row.finished_goods_store_audit_status === '2'">删除</el-button>
              <el-button size="small" type="success" @click="handleAudit(scope.row)"
              :disabled="scope.row.finished_goods_store_audit_status === '1' || scope.row.finished_goods_store_audit_status === '2'">审核</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- Centered pagination -->
      <div class="pagination-center">
        <el-pagination small v-model:current-page="currentPage" v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]" :background="true" layout="total, sizes, prev, pager, next, jumper"
          :total="pageCount" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- Audit Dialog -->
    <el-dialog v-model="centerDialogVisible" width="385" align-center header-align="left">
      <template #header>
        <div style="text-align: left; font-size: 16px; font-weight: bold;">
          审核
        </div>
      </template>
      <hr>
      <div style="text-align: left;padding: 10px 0px;">
        <p>审核结果</p>
        <div class="my-2 ml-4">
          <el-radio-group v-model="auditStatus">
            <el-radio value="1">通过</el-radio>
            <el-radio value="2">驳回</el-radio>
          </el-radio-group>
        </div>
        <div>
          <p>审核意见</p>
          <el-input v-model="auditOpinion" style="width: 350px;height: 90px;" :autosize="{ minRows: 4, maxRows: 4 }"
            type="textarea" placeholder="请输入" />
        </div>
      </div>
      <hr>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="updateAudit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, markRaw, toRaw } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { useStore } from 'vuex'
import { Delete } from '@element-plus/icons-vue'
import dayjs from 'dayjs'

export default {
  setup() {
    const tableData = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const pageCount = ref(0)
    const measureOptios = ref([])
    const Weahouse = ref([])
    const weahouseCode = ref("")
    const code = ref("")
    const userOptions = ref([])
    const store = useStore()
    const router = useRouter()
    const centerDialogVisible = ref(false)
    const auditStatus = ref('1')
    const auditOpinion = ref('')
    const finished_goods_store_id = ref(0)
    const customerTable = ref(null)
    const auditStatus1 = ref("")

    onMounted(() => {
      getMeasure()
      getUser()
      WeahousesSelect()
      fill()
      count()
    })

    function fill() {
      axios.get("http://localhost:5181/api/FG_Finished_Goods_Store/Get_Finished_Goods_Store_Infos", {
        params: {
          currentPage: currentPage.value,
          pageSize: pageSize.value,
          Warehouse_Code: weahouseCode.value,
          code: code.value,
          auditStatus: auditStatus1.value == "" ? '3' : auditStatus1.value
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        tableData.value = transformOthwrData(result.data)
      }).catch((err) => {
        console.error(err)
      })
    }

    function count() {
      axios.get("http://localhost:5181/api/FG_Finished_Goods_Store/Get_Finished_Goods_StoreCount", {
        params: {
          Warehouse_Code: weahouseCode.value,
          code: code.value,
          auditStatus: auditStatus1.value == "" ? '3' : auditStatus1.value
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        pageCount.value = result.data
      }).catch((err) => {
        console.error(err)
      })
    }

    const transformOthwrData = (responseData) => {
      const result = []

      responseData.forEach((mainItem) => {
        let store_total_qty = 0
        mainItem.details.forEach(detail => {
          store_total_qty += detail.store_qty || 0
        })

        mainItem.details.forEach((detail) => {
          result.push({
            finished_goods_store_id: mainItem.finished_goods_store_id,
            finished_goods_store_code: mainItem.finished_goods_store_code,
            warehouse_name: mainItem.warehouse_name,
            finished_goods_store_audit_status: mainItem.finished_goods_store_audit_status,
            pro_name: detail.pro_name,
            pro_code: detail.pro_code,
            pro_brand: detail.pro_brand,
            pro_model: detail.pro_model,
            measure_id: detail.measure_id,
            finished_goods_qty: detail.finished_goods_qty,
            unqualified_qty: detail.unqualified_qty,
            store_qty: detail.store_qty,
            quality_testing_status: mainItem.quality_testing_status,
            quality_testing_by: mainItem.quality_testing_by,
            quality_testing_time: mainItem.quality_testing_time,
            finished_goods_store_rep_id: mainItem.finished_goods_store_rep_id,
            store_total_qty: store_total_qty
          })
        })
      })

      return result
    }

    const objectSpanMethod = ({ row, column, rowIndex }) => {
      const fieldsToMerge = [
        "finished_goods_store_code",
        "warehouse_name",
        "finished_goods_store_audit_status",
        "store_total_qty",
        "quality_testing_status",
        "quality_testing_by",
        "quality_testing_time",
        "finished_goods_store_rep_id",
        "action"
      ]

      if (!fieldsToMerge.includes(column.property)) {
        return { rowspan: 1, colspan: 1 }
      }

      const currentGroup = row.finished_goods_store_code

      if (rowIndex === 0 || tableData.value[rowIndex - 1].finished_goods_store_code !== currentGroup) {
        let spanCount = 1

        while (
          rowIndex + spanCount < tableData.value.length &&
          tableData.value[rowIndex + spanCount].finished_goods_store_code === currentGroup
        ) {
          spanCount++
        }

        if (column.property === 'action') {
          return { rowspan: spanCount, colspan: 1 }
        }

        let sameValueCount = 1
        while (
          rowIndex + sameValueCount < tableData.value.length &&
          tableData.value[rowIndex + sameValueCount].finished_goods_store_code === currentGroup &&
          tableData.value[rowIndex + sameValueCount][column.property] === row[column.property]
        ) {
          sameValueCount++
        }

        return sameValueCount > 1
          ? { rowspan: sameValueCount, colspan: 1 }
          : { rowspan: 1, colspan: 1 }
      }
      else if (
        tableData.value[rowIndex - 1].finished_goods_store_code === currentGroup &&
        tableData.value[rowIndex - 1][column.property] === row[column.property]
      ) {
        return { rowspan: 0, colspan: 0 }
      }
      else {
        let sameValueCount = 1

        while (
          rowIndex + sameValueCount < tableData.value.length &&
          tableData.value[rowIndex + sameValueCount].finished_goods_store_code === currentGroup &&
          tableData.value[rowIndex + sameValueCount][column.property] === row[column.property]
        ) {
          sameValueCount++
        }

        return sameValueCount > 1
          ? { rowspan: sameValueCount, colspan: 1 }
          : { rowspan: 1, colspan: 1 }
      }
    }

    function handleSizeChange(val) {
      pageSize.value = val
      fill()
    }

    function handleCurrentChange(val) {
      currentPage.value = val
      fill()
    }

    function getMeasure() {
      axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
        params: {
          dict_type: "db_measure"
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        measureOptios.value = result.data
      }).catch((err) => {
        console.error(err)
      })
    }

    function measureValue(row) {
      if (!row) return "无"
      const parentDept = measureOptios.value.find((sex) => sex.dict_value == row)
      return parentDept ? parentDept.dict_label : "无"
    }

    function WeahousesSelect() {
      axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBySelect", {
        headers: {
          'Authorization': 'Bearer ' + localStorage.getItem('token')
        }
      }).then((res) => {
        Weahouse.value = res.data
      }).catch((err) => {
        console.error(err)
      })
    }

    function userValue(row) {
      if (!row) return "无"
      const parentUser = userOptions.value.find((user) => user.user_id == row)
      return parentUser ? parentUser.user_name : "无"
    }

    function getUser() {
      axios.get("http://localhost:5181/api/User/GetUsers", {
        params: {
          dept: 0,
          name: ""
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        userOptions.value = result.data
      }).catch((err) => {
        console.error(err)
      })
    }

    function query() {
      fill()
      count()
    }

    function reset() {
      weahouseCode.value = ""
      code.value = ""
      auditStatus1.value = ""
      query()
    }

    function addEdit() {
      router.push("/main/FG/FinishedGoodsStoreAdd")
    }

    function handleEdit(row) {
      if (row.finished_goods_store_audit_status != '0') {
        ElMessage.warning('已审核过的订单不能再次编辑！')
        return
      }
      store.commit("FinishedGoodsStoreCode", row.finished_goods_store_code)
      router.push("/main/FG/FinishedGoodsStoreUpdate")
    }

    function handleDelete(row) {
      if (row.finished_goods_store_audit_status != '0') {
        ElMessage.warning('已审核过的订单不允许进行删除！')
        return
      }
      ElMessageBox.confirm(
        '此操作将删除'+row.finished_goods_store_code+'信息，是否继续？',
        '警告',
        {
          type: 'warning',
          icon: markRaw(Delete),
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }
      )
        .then(() => {
          const loadingInstance = ElLoading.service({
            lock: true,
            text: '正在删除中...',
            background: 'rgba(0, 0, 0, 0.7)',
          });
          axios.put("http://localhost:5181/api/FG_Finished_Goods_Store/FG_Finished_Goods_StoreDel", {
            finished_goods_store_id: row.finished_goods_store_id,
            del_flag: '1'
          }, {
            headers: {
              authorization: `Bearer ${localStorage.getItem('token')}`
            }
          }).then((result) => {
            if (result.data > 0) {
              ElMessage.success('删除成功！')
              fill()
              count()
            }
          }).catch((err) => {
            console.error(err)
          }).finally(() => {
            loadingInstance.close();
          })
        })
        .catch(() => {
          ElMessage.info('已取消删除')
        })
    }

    function handleAudit(row) {
      if (row.finished_goods_store_audit_status != '0') {
        ElMessage.warning('已审核过的订单不能再次审核！')
        return
      }
      centerDialogVisible.value = true
      finished_goods_store_id.value = row.finished_goods_store_id
    }

    function updateAudit() {
      const loadingInstance = ElLoading.service({
        lock: true,
        text: '正在审核中...',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      axios.put("http://localhost:5181/api/FG_Finished_Goods_Store/FG_Finished_Goods_StoreUpdateAudit", {
        finished_goods_store_id: finished_goods_store_id.value,
        finished_goods_store_audit_by: localStorage.getItem('userLName'),
        finished_goods_store_audit_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
        finished_goods_store_audit_opinion: auditOpinion.value,
        finished_goods_store_audit_status: auditStatus.value
      }, {
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        if (result.data > 0) {
          if (auditStatus.value == '1') {
            ElMessage.success('审核通过')
          } else if (auditStatus.value == '2') {
            ElMessage.warning('审核已被驳回！')
          }
          close()
          fill()
          count()
        }
      }).catch((err) => {
        console.error(err)
      }).finally(() => {
        loadingInstance.close();
      })
    }

    function close() {
      auditOpinion.value = ""
      auditStatus.value = '1'
      centerDialogVisible.value = false
    }

    function infoPage(row) {
      store.commit("FinishedGoodsStoreCode", row)
      router.push("/main/FG/FinishedGoodsStoreInfo")
    }

    function getTableHeaders() {
      if (customerTable.value) {
        const filteredColumns = customerTable.value.columns.filter(column => {
          return column.label !== '操作'
        })
        const headers = filteredColumns.map(column => column.label)
        return headers
      }
      return []
    }

    const exportToExcel = async () => {
      const headers = getTableHeaders()
      const row = toRaw(tableData.value)
      const headerMap = {
        '成品入库编号': 'finished_goods_store_code',
        '入库仓库': "warehouse_name",
        '审核状态': 'finished_goods_store_audit_status',
        '产品名称': 'pro_name',
        '产品编号': 'pro_code',
        '品牌': 'pro_brand',
        '规格型号': 'pro_model',
        '单位': 'measure_id',
        '成品数量': 'finished_goods_qty',
        '不合格数量': 'unqualified_qty',
        '入库数量': 'store_qty',
        '入库总数': 'store_total_qty',
        '质检状态': 'quality_testing_status',
        '质检员': 'quality_testing_by',
        '质检时间': 'quality_testing_time',
        '入库员': 'finished_goods_store_rep_id',
      }

      const orderFields = [
        'finished_goods_store_code',
        'warehouse_name',
        'finished_goods_store_audit_status',
        'store_total_qty',
        'quality_testing_status',
        'quality_testing_by',
        'quality_testing_time',
        'finished_goods_store_rep_id'
      ]

      let previousOrderCode = null

      const rowDataArray = row.map((item, index) => {
        const rowData = headers.map(header => {
          const propName = headerMap[header]
          const currentOrderCode = item.finished_goods_store_code
          if (orderFields.includes(propName) && currentOrderCode === previousOrderCode) {
            return ''
          } else if (propName == "finished_goods_store_rep_id") {
            return userValue(item[propName])
          } else if (propName == "finished_goods_store_audit_status") {
            return item[propName] == '0' ? "待审核" :
              item[propName] == '1' ? "已审核" : "已驳回"
          } else if (propName == "quality_testing_status") {
            return item[propName] == '0' ? "不合格" :
              item[propName] == '1' ? "部分合格" : "全部合格"
          } else if (propName == "measure_id") {
            return measureValue(item[propName])
          } else {
            return item[propName]
          }
        })
        previousOrderCode = item.finished_goods_store_code
        return rowData
      })

      const mergeColumns = [
        '成品入库编号',
        '入库仓库',
        '审核状态',
        '入库总数',
        '质检状态',
        '质检员',
        '质检时间',
        '入库员'
      ]

      try {
        const response = await axios.post('http://localhost:5181/api/SystemHome/ExportExcel', {
          headers: headers,
          rows: rowDataArray,
          title: "成品入库信息",
          mergeColumns: mergeColumns
        }, {
          responseType: 'blob'
        })

        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', '成品入库信息.xlsx')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      } catch (error) {
        console.error('导出 Excel 失败:', error)
      }
    }

    return {
      tableData, currentPage, pageSize, pageCount, measureOptios, Weahouse,
      weahouseCode, code, userOptions, centerDialogVisible, auditStatus,
      auditOpinion, finished_goods_store_id, customerTable,
      fill, count, handleSizeChange, handleCurrentChange, measureValue,
      userValue, query, reset, addEdit, handleEdit, handleDelete, handleAudit,
      updateAudit, close, infoPage, exportToExcel, objectSpanMethod,auditStatus1
    }
  }
}
</script>

<style scoped>
.compact-container {
  padding: 10px;
}

.search-row {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 6px;
  margin-top: -40px;
}

.search-label {
  white-space: nowrap;
  font-size: 13px;
}

.search-input {
  width: 160px !important;
}

.search-select {
  width: 160px !important;
  margin-right: 6px;
}

.flex-grow {
  flex-grow: 1;
}

.table-wrapper {
  margin-top: 6px;
}

.pagination-center {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.action-group {
  display: flex;
  justify-content: center;
  gap: 4px;
}

.dialog-header {
  font-size: 16px;
  font-weight: bold;
  text-align: left;
}

.dialog-content {
  padding: 10px 0;
  text-align: left;
}

.radio-group {
  margin: 10px 0 20px 0;
}

.opinion-input {
  width: 100%;
  margin-top: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-table__row) {
  height: 36px !important;
}

:deep(.el-table th.el-table__cell) {
  height: 36px !important;
}

:deep(.el-button--small) {
  padding: 5px 8px;
  height: 24px;
}
</style>